interface IPageData {
  story: {
    id: number;
    name: string;
    coverImage: string;
    content: string;
    readCount: number;
    favoriteCount: number;
    isFavorite: boolean;
    ttsUrl: string;
  };
  isPlaying: boolean;
  playProgress: number;
}

Page<IPageData>({
  data: {
    story: {},
    isPlaying: false,
    playProgress: 0
  },

  async onLoad(options) {
    const storyId = options.id;
    await this.fetchStoryDetail(storyId);
    await this.fetchUserCollect(storyId);
    this.addViewsCount(storyId);
  },
  async fetchUserCollect(detailId: String) {
    // 获取用户收藏
    const userId = wx.getStorageSync('userId');; // 这里应该从本地存储获取userId

    wx.request({
      url: 'https://fairy.ymdx.cn/v1/fairy/queryCollect',
      method: 'POST',
      data: { userId, detailId },
      success: (res: any) => {
        if (res.data.code === 200 && res.data.data) {
          this.setData({
            'story.isFavorite': true
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络请求失败',
          icon: 'error'
        });
      }
    });
  },
  async fetchStoryDetail(storyId: string) {
    await wx.request({
      url: 'https://fairy.ymdx.cn/v1/fairy/detail',
      method: 'POST',
      data: { id: storyId },
      success: (res: any) => {
        if (res.data.code === 200 && res.data.data) {
          const storyData = res.data.data;
          this.setData({
            story: {
              id: storyData.id,
              name: storyData.name,
              coverImage: storyData.thumbnail,
              content: storyData.content.replace(/<p>/g, '<p style="text-indent: 2em;">'),
              readCount: storyData.views,
              favoriteCount: storyData.collects,
              isFavorite: false, // 默认未收藏，后续可以通过接口获取收藏状态
              ttsUrl: storyData.ttsUrl
            }
          });
        } else {
          wx.showToast({
            title: '获取故事详情失败',
            icon: 'error'
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络请求失败',
          icon: 'error'
        });
      }
    });
  },

  goBack() {
    wx.navigateBack();
  },
  async addViewsCount(id: number) {
    try {
      const response = await new Promise((resolve, reject) => wx.request({
        url: 'https://fairy.ymdx.cn/v1/fairy/addViews',
        method: 'POST',
        data: { id },
        success: function(res) {
          resolve(res);
        },
        fail: function(err) {
          reject(err);
        }
      }));

      if (!response.data || response.data.code !== 200) {
        throw new Error(response.data?.msg || '增加浏览量失败');
      }
    } catch (error) {
      console.error('增加浏览量失败:', error);
    }
  },
  async toggleFavorite() {
    const newFavoriteState = !this.data.story.isFavorite;
    const userId = wx.getStorageSync('userId');; // 这里应该从本地存储获取userId
    const detailId = this.data.story.id;

    try {
      const response = await new Promise((resolve, reject) => wx.request({
        url: 'https://fairy.ymdx.cn/v1/fairy/toggleCollect',
        method: 'POST',
        data: { userId, detailId },
        success: function(res) {
          resolve(res);
        },
        fail: function(err) {
          reject(err);
        }
      }));

      if (response.data && response.data.code === 200) {
        this.setData({
          'story.isFavorite': newFavoriteState,
          'story.favoriteCount': newFavoriteState 
            ? this.data.story.favoriteCount + 1
            : this.data.story.favoriteCount - 1
        });

        wx.showToast({
          title: newFavoriteState ? '已收藏' : '已取消收藏',
          icon: 'success'
        });
      } else {
        throw new Error(response.data?.msg || '操作失败');
      }
    } catch (error) {
      console.error('收藏操作失败:', error);
      wx.showToast({
        title: '操作失败',
        icon: 'error'
      });
    }
  },

  shareStory() {
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    });
  },

  onShareAppMessage() {
    const { name, id } = this.data.story;
    return {
      name: name,
      path: `/pages/story/story?id=${id}`,
      imageUrl: this.data.story.coverImage
    };
  },

  onShareTimeline() {
    const { name, id } = this.data.story;
    return {
      name: name,
      query: `id=${id}`,
      imageUrl: this.data.story.coverImage
    };
  },

  audioContext: null as any,

  onLoad(options) {
    const storyId = options.id;
    this.initAudioContext();
    this.fetchStoryDetail(storyId);
    this.fetchUserCollect(storyId);
    this.addViewsCount(storyId);
  },

  initAudioContext() {
    if (this.audioContext) {
      this.audioContext.destroy();
      this.audioContext = null;
    }
    this.audioContext = wx.createInnerAudioContext();
    this.audioContext.onTimeUpdate(() => {
      if (this.audioContext && this.audioContext.duration > 0) {
        const progress = ((this.audioContext.currentTime / this.audioContext.duration) * 100).toFixed(2);
        this.setData({
          playProgress: parseFloat(progress)
        });
      }
    });
    this.audioContext.onEnded(() => {
      this.setData({
        isPlaying: false,
        playProgress: 0
      });
    });
  },

  togglePlay() {
    if (!this.audioContext || !this.data.story.ttsUrl) {
      return;
    }

    if (!this.audioContext.src) {
      this.audioContext.src = this.data.story.ttsUrl;
    }

    if (this.data.isPlaying) {
      this.audioContext.pause();
    } else {
      this.audioContext.play();
    }

    this.setData({
      isPlaying: !this.data.isPlaying
    });
  },

  onUnload() {
    if (this.audioContext) {
      try {
        this.audioContext.stop();
        this.audioContext.destroy();
        this.audioContext = null;
      } catch (error) {
        console.error('Error destroying audio context:', error);
      }
    }
  }
});